<template>
  <el-container>
    <!--  首部  -->
    <div id="logoin">
      <!-- 导航栏按钮 -->
      <div id="daoHang" style="box-shadow: rgba(0, 0, 0, 0.1) 0px 2px 12px 0px; margin-bottom: 4vh;">
        <div class="ww el-row" style="padding: 15px; line-height: 76px;">
          <div class="el-col el-col-12">
            <ul class="imgStyle clearfix">
              <li><img alt="" class="logo" src="../assets/logo.png" lazy="loaded" @click="goHome">
              </li>
              <li><img alt="" class="textImg" src="../assets/系统.png" lazy="loaded"></li>
            </ul>
          </div>
          <div class="el-col el-col-12" style="text-align: right;">
            <!-- <el-button type="primary" @click="userInfo()">查看个人信息</el-button> -->
            <el-button type="primary" @click="userManager()">查看场地预约</el-button>
          </div>
        </div>
      </div>
    </div>
    <!-- 内容体 -->
    <!-- 弹框 -->
    <div id="windows">
      <!-- 场地预约管理抽屉 -->
      <el-drawer class="info" title="场地预约管理" :visible.sync="drawerMang" direction="btt" size="45%"
        style="font-weight: bold;">
        <div>
          <el-table :data="tableData" style="width: 100%; table-layout: fixed; text-align: center;"
            :row-class-name="tableRowClassName">
            <el-table-column align="center" prop="gId" label="场地名称">
            </el-table-column>
            <el-table-column align="center" prop="tId" label="预约时间段">
            </el-table-column>
            <el-table-column align="center" prop="pDate" label="预约日期">
            </el-table-column>
            <el-table-column align="center" prop="pState" label="当前状态">
            </el-table-column>
            <el-table-column align="center" fixed="right" label="操作">
              <template slot-scope="scope">
                <el-button type="danger" size="small" @click="downP(scope.$index, tableData)"
                  :disabled="scope.row.pState === '预约已失效'">退订</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-drawer>
    </div>
    <el-main>
      <div class="w">
        <div class="isyy">预约选项</div>
        <!---->
        <el-row style="margin-bottom: 30px">
          <!-- 校区选择 -->
          <div class="isyy">
            <span class="isyy">校区：</span>
            <el-radio-group v-model="searchParms.cCampus" size="small">
              <el-radio-button label="全部">全部</el-radio-button>
              <el-radio-button label="文昌校区">文昌校区</el-radio-button>
              <el-radio-button label="柳东校区">柳东校区</el-radio-button>
              <el-radio-button label="柳石校区">柳石校区</el-radio-button>
            </el-radio-group>
          </div>
          <!-- 类型选择 -->
          <div class="isyy">
            <span class="isyy">类型：</span>
            <el-radio-group v-model="searchParms.cType" size="small">
              <el-radio-button label="全部">全部</el-radio-button>
              <el-radio-button label="舞蹈">舞蹈</el-radio-button>
              <el-radio-button label="足球">足球</el-radio-button>
              <el-radio-button label="篮球">篮球</el-radio-button>
              <el-radio-button label="排球">排球</el-radio-button>
              <el-radio-button label="网球">网球</el-radio-button>
              <el-radio-button label="飞盘">飞盘</el-radio-button>
              <el-radio-button label="羽毛球">羽毛球</el-radio-button>
              <el-radio-button label="乒乓球">乒乓球</el-radio-button>
            </el-radio-group>
          </div>
        </el-row>

        <el-row>

          <div>
            <div class="fl isyy">场馆列表</div>
          </div>

          <!-- 页面展示 -->
          <div class="el-col el-col-24">

            <el-row :gutter="30" style="margin-left: 39px;">
              <el-col style="display: flex; margin:15px 0px; height:268px; width:285px;" :span="10"
                v-for="item in this.groundData" :key="item.id">
                <el-card :body-style="{ padding: '0px' }" style="flex-wrap: 4;">
                  <img :src="'GroundPages/' + item.id + '.jpg'" class="image" style="width: 250px;height:180px;">
                  <div style="padding: 14px;">
                    <span>{{ item.cName }} </span>
                    <span> {{ item.cCampus }}</span>
                    <div class="bottom clearfix">
                      <el-button @click="handleCardClick(item)" style="left: 50%; " type="text"
                        class="button">点击预约</el-button>
                    </div>
                  </div>
                </el-card>
              </el-col>
            </el-row>

          </div>
        </el-row>
      </div>
    </el-main>
    <!-- 分页体 -->
    <el-footer>
      <!-- 分页 -->
      <div class="is">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="this.searchParms.pageNum" :page-sizes="[2, 4, 6, 8]" :page-size="this.searchParms.pageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="this.total">
        </el-pagination>
      </div>
      <div class="iss">@软件214覃文昌</div>

      <!-- 表单 -->
      <el-drawer size="42%" title="预约场地" :visible.sync="drawer" direction="ltr">

        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">

          <el-form-item label="场地名称:" prop="name">
            {{ this.NowgroundData.cName }} {{ this.NowgroundData.cCampus }}
          </el-form-item>

          <el-form-item label="场地实景:">

            <div>
              <span class="demonstration"></span>
              <el-image style="width: 360px; height: 250px;" :src="'GroundPages/' + this.NowgroundData.id + '.jpg'"
                fit="contain"></el-image>
            </div>

          </el-form-item>

          <el-form-item label="活动时间" required>
            <el-col :span="11">
              <el-form-item prop="p_date">
                <el-date-picker value-format="yyyy-MM-dd" type="date" placeholder="选择日期" v-model="ruleForm.p_date"
                  style="width: 80%;"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col class="line" :span="2">-</el-col>
            <el-col :span="11">
              <el-form-item prop="t_id">
                <el-select v-model="ruleForm.t_id" placeholder="选择时间段" style="width: 80%;">
                  <el-option v-for="item in this.option" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')">立即预约</el-button>
            <el-button @click="cancel">取消</el-button>
          </el-form-item>
        </el-form>
        {{ this.ruleForm }}
      </el-drawer>
    </el-footer>
    <!--  尾部   -->
    <div class="footer" id="end" style="background: #f9f9f9;color: #7e8187;">
      <div class="container container-lg clearfix">
        <div class="pull-left footer-left" style="margin-right: 22px; margin-top: 20px">
          <div class="footer-tt">文昌校区</div>
          <p>地址: 广西柳州市城中区文昌路2号</p>
          <p>邮编: 545006</p>
        </div>
        <div class="pull-left footer-left" style="margin-right: 22px; margin-top: 20px">
          <div class="footer-tt">柳石校区</div>
          <p>地址: 广西柳州市鱼峰区柳石路257号</p>
          <p>邮编: 545005</p>
        </div>
        <div class="pull-left footer-left" style="margin-right: 22px; margin-top: 20px">
          <div class="footer-tt">柳东校区</div>
          <p>地址: 广西柳州市鱼峰区官塘大道19号</p>
          <p>邮编: 545616</p>
        </div>
        <div class="pull-right footer-right" style="margin-top: 20px">
          <p><span>电话: </span>0772-2685979（校办）&nbsp;&nbsp;0772-2687698（传真）
          </p>
          <p>本专科招生: 0772—2687735&nbsp;&nbsp;研究生招生: 0772—2685375</p>
          <p>继续教育招生: 0772—2686688</p>
        </div>
      </div>
      <div class="footer-bottom text-center">备案号: <img src="../assets/footer01.png" alt="">桂XXX备XXXXXXXX号-x<img
          src="../assets/footer02.png">前置审核编号:
        桂xxxxxxxx-xx<span>信息管理: 没人管理</span>
      </div>
    </div>
  </el-container>
</template>
  

<style scoped>
.w {
  width: 1230px;
  height: 600px;
  margin: 0 auto;
}

.fl {
  float: left;
}

.fr {
  float: right;
}

.isyy {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 20px;
  text-align: left;
}

.is {
  height: 40px;
  line-height: 40px;
  color: #7e8187;
  text-align: center;
  font-size: 12px;
  background: #f9f9f9;
  bottom: 0;
  width: 100%
}

/* 场地展示 */
.time {
  font-size: 13px;
  color: #999;
}

.bottom {
  margin-top: 10px;
  line-height: 9px;
}

.button {
  padding: 0;
  float: right;
}

.image {
  width: 100%;
  display: block;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}
</style>


<script>
function Node(gId, tId, pDate, pState, GID, TID, PDATE) {
  this.gId = gId;
  this.tId = tId;
  this.pDate = pDate;
  this.pState = pState;
  this.GID = GID;
  this.TID = TID;
  this.PDATE = PDATE;
}
import {
  getGround,
  saveOrUpdate,
  postUserInfo,
  postUpdateInfo,
  postPInfo,
  postUpdateP
} from "@/api/base/user"

export default {
  data() {
    return {
      //时间选项
      option: [
        {
          value: 1,
          label: "9:00-11:00",
        },
        {
          value: 2,
          label: "14:00-16:00",
        },
        {
          value: 3,
          label: "16:00-18:00",
        },
        {
          value: 4,
          label: "18:00-20:00",
        },
        {
          value: 5,
          label: "20:00-22:00",
        },
      ],
      //抽屉
      drawer: false,
      //当前选择的场地数据
      NowgroundData: {
        id: "",
        cost: "",
        state: "",
        cName: "",
        cCampus: "",
        cType: "",
      },
      //存放场地信息
      groundData: [
        {
          id: "",
          cost: "",
          state: "",
          cName: "",
          cCampus: "",
          cType: "",
        },
      ],
      input: "",
      total: 0,
      //查询条件
      searchParms: {
        cCampus: this.$route.params.School == null ? "全部" : this.$route.params.School,
        cType: this.$route.params.Type == null ? "全部" : this.$route.params.Type,
        pageNum: 1,
        pageSize: 8,
      },
      //表单数据
      ruleForm: {
        g_id: '',
        t_id: '',
        p_date: '',
      },
      rules: {
        p_date: [
          { required: true, message: '请选择日期', trigger: 'change' }
        ],
        t_id: [
          { required: true, message: '请选择时间', trigger: 'change' }
        ],
      },
      currentPage4: 1,
      // 抽屉背景
      drawerBgStyle: {
        backgroundImage: 'url(' + require('../assets/drawer_bg.png') + ')',
        backgroundRepeat: 'no-repeat',
        backgroundPosition: 'center',
        backgroundSize: 'cover',
      },
      // 背景模糊
      blurEnabled: false,
      // 窗口可见
      dialogFormVisible_user: false,
      dialogFormVisible_admin: false,
      dialogFormVisible_register: false,
      dialogFormVisible_forgetPSW: false,
      // 验证码按钮
      getCode_on: true,
      getCode_dis: false,
      time: 60,
      // 个人信息抽屉
      drawerUser: false,
      drawerMang: false,
      lockInfo: true,
      // 个人信息
      userInfoForm: {
        uname: '',
        age: '保密',
        sex: '保密',
        college: '保密',
        cla: '保密',
        credit: 0,
        mobile: '',
        psw: ''
      },
      // 预约场地信息表
      tableData: []
    };
  },
  methods: {
    //分页
    handleSizeChange(val) {
      this.searchParms.pageSize = val;
      console.log(`每页 ${val} 条`);
      this.init();
    },
    handleCurrentChange(val) {
      this.searchParms.pageNum = val;
      console.log(`当前页: ${val}`);
      this.init();
    },
    //获取当前点击选择的场地数据
    handleCardClick(item) {
      this.resetForm('ruleForm');
      this.NowgroundData.id = item.id;
      this.NowgroundData.cName = item.cName;
      this.NowgroundData.cCampus = item.cCampus;
      this.NowgroundData.cost = item.cost;
      this.NowgroundData.cType = item.cType;
      this.NowgroundData.state = item.state;
      this.getFormData();
      console.log(this.NowgroundData);
    },
    //给表单赋值
    getFormData() {
      this.ruleForm.g_id = this.NowgroundData.id;
      this.drawer = true;
    },
    //查询数据
    async init() {
      let temp = {
        ...this.searchParms,
      };
      const token = localStorage.getItem('token');
      let res = await getGround(temp, token);
      this.groundData = res.data.list;
      console.log(this.groundData);
      this.total = res.data.total;
      console.log(this.total);

    },
    //预约场地
    booking() {
      this.drawer = true;
    },
    //预定表单
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          // 发送数据给后端
          const token = localStorage.getItem('token');
          let res = await saveOrUpdate(this.ruleForm, token);
          if (res.code == 200) {
            //保存成功：
            //提示用户
            this.$notify.success({
              title: "成功",
            });
            //表单重置
            this.resetForm('ruleFrom');
            this.drawer = false;
          }else{
            this.$notify.error({
            title: "该时间已被预约，请选择其他时间段",
          });
          }
        } else {
          //保存失败，提示用户
          this.$notify.error({
            title: "错误",
          });
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      if (this.$refs[formName] !== undefined) {
        this.$refs[formName].resetFields();
      }
    },
    //取消
    cancel() {
      this.$confirm('确认取消预约？')
        .then(_ => {
          this.drawer = false;
          this.resetForm('ruleForm');
        })
        .catch(_ => { });
    },
    // 用户信息更新--成功
    updateInfoSucceed() {
      this.$notify({
        title: '你有一个通知~',
        message: '信息更新完毕(*^_^*)~',
        position: 'top-left',
        type: 'success'
      });
    },
    // 用户信息更新--未知错误
    updateInfoError() {
      this.$notify.error({
        title: '你有一个警告！',
        message: '信息更新出错啦！！',
        position: 'top-left',
      });
    },
    // 用户信息请求
    async getUserInfo() {
      const token = localStorage.getItem('token');
      let res = await postUserInfo(this.userInfoForm, token);
      this.userInfoForm.uname = res.data.uname;
      if (res.data.sex == 0) {
        this.userInfoForm.sex = "女生";
      } else if (res.data.sex == 1) {
        this.userInfoForm.sex = "男生";
      } else {
        this.userInfoForm.sex = "保密";
      }
      if (res.data.college == null || res.data.college == "") {
        this.userInfoForm.college = "保密";
      } else {
        this.userInfoForm.college = res.data.college;
      }
      if (res.data.cla == null || res.data.cla == "") {
        this.userInfoForm.cla = "保密";
      } else {
        this.userInfoForm.cla = res.data.cla;
      }
      if (res.data.age == 0) {
        this.userInfoForm.age = "保密";
      } else {
        this.userInfoForm.age = res.data.age;
      }
      this.userInfoForm.credit = res.data.credit;
      this.userInfoForm.mobile = res.data.mobile;
    },
    // 点击个人信息管理页面
    async userInfo() {
      await this.getUserInfo();
      this.drawerUser = true;
    },
    // 点击个人页面-信息编辑
    editerInfo() {
      this.lockInfo = false;
    },
    // 用户信息更新请求
    async updateInfo() {
      let t = {
        uname: this.userInfoForm.uname,
        age: this.userInfoForm.age,
        sex: this.userInfoForm.sex,
        college: this.userInfoForm.college,
        cla: this.userInfoForm.cla,
        credit: this.userInfoForm.credit,
        mobile: this.userInfoForm.mobile
      }
      if (t.age == "保密")
        t.age = 0;
      if (t.college == "保密")
        t.college = null;
      if (t.cla == "保密")
        t.cla = null;
      if (t.sex == "女生")
        t.sex = 0;
      else if (t.sex == "男生")
        t.sex = 1;
      const token = localStorage.getItem('token');
      let res = await postUpdateInfo(t, token);
      if (res.data == "Success")
        this.updateInfoSucceed();
      else
        this.updateInfoError();
    },
    // 点击个人页面-保存信息
    async saveInfo() {
      this.lockInfo = true;
      this.updateInfo();
    },
    // 点击个人预约管理
    async userManager() {
      await this.getUserInfo();
      const token = localStorage.getItem('token');
      let t = {
        uname: this.userInfoForm.uname,
        age: this.userInfoForm.age,
        sex: this.userInfoForm.sex,
        college: this.userInfoForm.college,
        cla: this.userInfoForm.cla,
        credit: this.userInfoForm.credit,
        mobile: this.userInfoForm.mobile
      }
      if (t.age == "保密")
        t.age = 0;
      if (t.college == "保密")
        t.college = null;
      if (t.cla == "保密")
        t.cla = null;
      if (t.sex == "女生")
        t.sex = 0;
      else if (t.sex == "男生")
        t.sex = 1;
      let res = await postPInfo(t, token);
      this.tableData = [];
      for (let i = 0; i < res.data.length; i++) {
        let p_datee = new Date(res.data[i].p_date).toISOString().slice(0, 10);
        p_datee = new Date(p_datee).setDate(new Date(p_datee).getDate() + 1);
        p_datee = new Date(p_datee).toISOString().slice(0, 10);
        let state;
        if (res.data[i].p_state == 1) {
          state = "已预约"
        } else {
          state = "预约已失效"
        }
        this.tableData.push(new Node(res.data[i].c_name, res.data[i].start_time + "~" + res.data[i].end_time, p_datee, state, res.data[i].g_id, res.data[i].t_id, p_datee))
      }
      this.dialogFormVisible_schedule = true;
      this.drawerMang = true;
    },
    // 场地预约管理的状态列
    tableRowClassName({ row }) {
      if (row.pState === '预约已失效') {
        return 'warning-row';
      } else if (row.pState === '已预约') {
        return 'success-row';
      }
      return '';
    },
    // 发送更新预约请求
    async sendUpdateP(GID, TID, PDATE) {
      const token = localStorage.getItem('token');
      await postUpdateP({ "GID": GID, "TID": TID, "PDATE": PDATE }, token);
      this.userManager();
    },
    // 取消预订提示框
    async downP(index, rows) {
      this.$confirm('是否确认取消预订？', '错做不可逆', {
        cancelButtonText: '点错了',
        confirmButtonText: '取消预定',
        type: 'warning'
      }).then(() => {
        this.sendUpdateP(rows[index].GID, rows[index].TID, rows[index].PDATE);
        this.$message({
          type: 'success',
          message: '已取消预订!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '不取消我们就是好朋友!'
        });
      });
    },
    // 跳转主页面
    goHome() {
      this.$router.push('/')
    },
    // 登录校验
    async hasLoad() {
      this.token = localStorage.getItem('token');
      if (this.token != null)
        await this.getUserInfo();
      else
        this.$router.push({ name: 'GXUSTVRS', params: { dialogFormVisible_user: true } })
    }
  },


  //监听searchParms的变化
  watch: {
    searchParms: {
      async handler() {
        await this.init();
      },
      deep: true,
    },
  },
  created() {
    this.init();
    this.hasLoad();
  },
  mounted() {

  },
};
</script>